const api = require('api.js');

var messages;

var pushEnabled = true;

export function init() {
	try {
		pushEnabled = Boolean.parse(uni.getStorageSync('pushMessage'));
	} catch (err) {
		pushEnabled = true;
	}
	try {
		messages = JSON.parse(uni.getStorageSync('messages'));
	} catch (err) {
		messages = null;
	}
	if (messages == undefined || messages == null) {
		messages = [];
		loadMessageList();
	}
}

export function setPushEnabled(value) {
	pushEnabled = value;
}

export function isPushEnabled() {
	return pushEnabled;
}

export function readMessage(idx) {
	api.getAsync('/api/message/read/' + messages[idx].id, {}, (res)=>{},(err)=>{})
	messages[idx].isRead = true;
	saveMessages();
}

export function deleteMessage(idx) {
	api.getAsync('/api/message/delete/' + messages[idx].id, {}, (res)=>{},(err)=>{})
	messages.splice(idx, 1);
	saveMessages();
}

export function saveMessages() {
	uni.setStorage({
		key: 'messages',
		data: JSON.stringify(messages)
	})
}

export function clearLocalStorage() {
	uni.removeStorage({
		key: 'messages'
	})
}

var onMessageLoaded = null;

export function loadMessageList() {
	api.getAsync('/api/message/my', {}, (res) => {
		if (res.code == 200) {
			messages = res.data;
			if (onMessageLoaded) {
				try {
					onMessageLoaded(messages);
				} catch (err) {
					
				}
			}
			saveMessages();
		}
	}, (err) => {});
}

export function listenMessageLoaded(func) {
	onMessageLoaded = func;
}

export function getMessageListCached() {
	return messages;
}

export function hasNewMessage() {
	if (messages) {
		for (var i = 0; i < messages.length; i++) {
			if (!messages[i].isRead) {
				return true;
			}
		}
	}
	return false;
}